<script setup>
import {useRoute} from 'vue-router'
import {ref, onMounted} from 'vue'
import {getBatchDetail} from '@/api/uploadRecord.js'

const route = useRoute()
const itemId = route.params.id
const data = ref({})
const loading = ref(true)
const error = ref(null)

// 将API数据转换为前端所需格式
const transformApiData = (apiData) => {
  const taskBatch = apiData.taskBatch
  const detectImageResults = apiData.detectImageResults

  // 处理质量等级分布
  let qualityGradeDistribution = {}
  try {
    qualityGradeDistribution = JSON.parse(taskBatch.qualityGradeDistribution || '{}')
  } catch (e) {
    console.error('Error parsing qualityGradeDistribution:', e)
  }

  // 处理风险等级分布
  let riskLevelDistribution = {}
  try {
    riskLevelDistribution = JSON.parse(taskBatch.riskLevelDistribution || '{}')
  } catch (e) {
    console.error('Error parsing riskLevelDistribution:', e)
  }

  // 处理批次建议
  let batchRecommendations = []
  try {
    batchRecommendations = JSON.parse(taskBatch.batchRecommendations || '[]')
  } catch (e) {
    console.error('Error parsing batchRecommendations:', e)
  }

  // 构建图片详情数据
  const data_details = detectImageResults.map(result => {
    let defects = []
    try {
      // 解析检测JSON
      const detectionData = JSON.parse(result.detectionJson || '[]')
      defects = detectionData.map((defect, index) => ({
        defect_number: index + 1,
        defect_type: `${defect.class_name}（${defect.severity?.description || '未知类型'}）`,
        defect_feature: {
          location: `bbox坐标为 (x1=${defect.bbox?.x1 || 0}, y1=${defect.bbox?.y1 || 0}, x2=${defect.bbox?.x2 || 0}, y2=${defect.bbox?.y2 || 0})`,
          area: `${defect.area_percentage || 0}%`,
          degree: `${defect.confidence || 0}`
        },
        defect_level: `${defect.severity?.level || '未知'}`,
        defect_analysis: result.defectDetails ? result.defectDetails.split('• 成因分析：')[1]?.split('•')[0]?.trim() || '无详细分析' : '无详细分析',
        defect_suggestion: result.defectDetails ? result.defectDetails.split('• 改进建议：')[1]?.trim() || '无改进建议' : '无改进建议'
      }))
    } catch (e) {
      console.error('Error parsing detectionJson:', e)
    }

    return {
      p_index: result.imageIndex + 1,
      p_level: result.qualityGrade?.replace('级', '') || '无',
      p_score: result.qualityScore || 0,
      p_risk: result.riskLevel === 'low' ? '低风险' :
          result.riskLevel === 'medium' ? '中风险' :
              result.riskLevel === 'high' ? '高风险' : '未知风险',
      p_defect: result.detectionCount || 0,
      p_defectType: defects.length > 0 ? defects[0].defect_type.split('（')[0] : '无缺陷',
      p_descript: result.imageSummary || result.improvementSuggestions || '无描述',
      p_details: defects,
      rawImageUrl: result.rawImageUrl || '' // 添加原图URL
    }
  })

  // 计算合格率
  const passRate = taskBatch.passRate !== undefined ?
      taskBatch.passRate :
      (taskBatch.imageCount - taskBatch.totalDefects) / taskBatch.imageCount * 100

  return {
    data_number: taskBatch.id,
    data_time: taskBatch.createdAt ? taskBatch.createdAt.split(' ')[0] : '未知日期',
    data_model: taskBatch.detectionModel || '未知模型',
    data_count: taskBatch.imageCount || 0,
    data_totalError: taskBatch.totalDefects || 0,
    data_passrate: `${passRate.toFixed(1)}%`,
    data_finalScore: taskBatch.qualityScore || 0,
    data_general: taskBatch.batchSummary || '无总体结论',
    data_details: data_details,
    data_suggestion: taskBatch.overallSuggestions || taskBatch.analysisReport || '无建议'
  }
}

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    const response = await getBatchDetail(itemId)

    if (response.code === 0) {
      data.value = transformApiData(response.data)
    } else {
      error.value = response.message || '获取数据失败'
    }
  } catch (err) {
    error.value = '网络错误，请稍后重试'
    console.error('Error fetching batch detail:', err)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<template>
  <div class="all-page">
    <div class="detail-container">
      <button class="back-btn" @click="$router.back()">{{ $t("detail-back") }}</button>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading">加载中...</div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error">
        <h1>错误</h1>
        <p>{{ error }}</p>
        <button @click="fetchData">重试</button>
      </div>

      <!-- 正常状态 -->
      <div v-else>
        <h1>{{ $t("detail-title") }}</h1>

        <!-- 基本信息 -->
        <section class="section">
          <h2>{{ $t("detail-section1") }}</h2>
          <p><strong>{{ $t("detail-datanumber") }}：</strong>{{ data.data_number }}</p>
          <p><strong>{{ $t("detail-datatime") }}：</strong>{{ data.data_time }}</p>
          <p><strong>{{ $t("detail-datamodel") }}：</strong>{{ data.data_model }}</p>
          <p><strong>{{ $t("detail-datacount") }}：</strong>{{ data.data_count }}</p>
          <p><strong>{{ $t("detail-dataerror") }}：</strong>{{ data.data_totalError }}</p>
          <p><strong>{{ $t("detail-datarate") }}：</strong>{{ data.data_passrate }}</p>
          <p><strong>{{ $t("detail-datascore") }}：</strong>{{ data.data_finalScore }}</p>
        </section>

        <!-- 总体结论 -->
        <section class="section">
          <h2>{{ $t("detail-section2") }}</h2>
          <p>{{ data.data_general }}</p>
        </section>

        <!-- 图片逐一详情 -->
        <section class="section">
          <h2>{{ $t("detail-section3") }}</h2>
          <div v-for="(item, index) in data.data_details" :key="index" class="image-block">
            <h3>{{ $t("detail-image") }} {{ item.p_index }}</h3>

            <!-- 添加原图预览 -->
            <div v-if="item.rawImageUrl" class="image-preview">
              <p><strong>原图预览：</strong></p>
              <img :src="item.rawImageUrl" :alt="`图片${item.p_index}原图`" class="preview-image"
                   @click="openImage(item.rawImageUrl)"/>
            </div>

            <p><strong>{{ $t("detail-level") }}：</strong>{{ item.p_level }}</p>
            <p><strong>{{ $t("detail-score") }}：</strong>{{ item.p_score }}</p>
            <p><strong>{{ $t("detail-risk") }}：</strong>{{ item.p_risk }}</p>
            <p><strong>{{ $t("detail-number") }}：</strong>{{ item.p_defect }}</p>
            <p><strong>{{ $t("detail-mainError") }}：</strong>{{ item.p_defectType }}</p>
            <p><strong>{{ $t("detail-description") }}：</strong>{{ item.p_descript }}</p>

            <!-- 缺陷详情 -->
            <div v-if="item.p_details && item.p_details.length > 0">
              <h4>{{ $t("detail-details") }}</h4>
              <div v-for="(defect, defectIndex) in item.p_details" :key="defectIndex" class="defect-block">
                <p><strong>{{ $t("detail-index") }}：</strong>{{ defect.defect_number }}</p>
                <p><strong>{{ $t("detail-type") }}：</strong>{{ defect.defect_type }}</p>
                <p><strong>{{ $t("detail-feature") }}：</strong></p>
                <ul>
                  <li><strong>{{ $t("detail-area") }}：</strong>{{ defect.defect_feature.location }}</li>
                  <li><strong>{{ $t("detail-propotion") }}：</strong>{{ defect.defect_feature.area }}</li>
                  <li><strong>{{ $t("detail-coefficient") }}：</strong>{{ defect.defect_feature.degree }}</li>
                </ul>
                <p><strong>{{ $t("detail-degree") }}：</strong>{{ defect.defect_level }}</p>
                <p><strong>{{ $t("detail-analysis") }}：</strong>{{ defect.defect_analysis }}</p>
                <p><strong>{{ $t("detail-suggestion") }}：</strong>{{ defect.defect_suggestion }}</p>
              </div>
            </div>
          </div>
        </section>

        <!-- 综合建议 -->
        <section class="section">
          <h2>{{ $t("detail-section4") }}</h2>
          <pre class="suggestion">{{ data.data_suggestion }}</pre>
        </section>
      </div>
    </div>
  </div>
</template>

<style scoped>
.all-page {
  width: 100%;
  height: auto;
  min-height: 100vh;
  background-color: var(--wrap-bg);
}

.detail-container {
  max-width: 900px;
  margin: auto;
  padding: 20px;
  font-family: Arial, sans-serif;
  line-height: 1.6;
  background-color: var(--bgcolor);
  position: relative;
}

.back-btn {
  position: absolute;
  top: 20px;
  left: 20px;
  background-color: var(--button-bg);
  color: white;
  border: none;
  padding: 8px 14px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.loading, .error {
  text-align: center;
  padding: 40px;
  color: var(--txcolor);
}

.error button {
  background-color: var(--button-bg);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  margin-top: 20px;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
  color: var(--txcolor);
  transition: color 0.3s ease;
}

.section {
  margin-bottom: 30px;
  padding: 15px;
  border-radius: 8px;
  background-color: var(--card-bg);
  transition: background-color 0.3s ease;
}

.section h2 {
  border-left: 4px solid var(--accent-color);
  padding-left: 10px;
  margin-bottom: 15px;
  font-size: 20px;
  color: var(--h3-color);
  transition: color 0.3s ease, border-color 0.3s ease;
}

.section p {
  color: var(--history-text-primary);
  transition: color 0.3s ease;
}

.section strong {
  color: var(--history-text-secondary);
  transition: color 0.3s ease;
}

.section h4 {
  color: var(--history-text-secondary);
  transition: color 0.3s ease;
}

.image-block {
  background: var(--history-card-bg);
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 8px;
  border: 1px solid var(--history-border);
  transition: background-color 0.3s ease, border-color 0.3s ease;
}

.image-block h3 {
  margin-top: 0;
  color: var(--h3-color);
  transition: color 0.3s ease;
}

.image-block p {
  color: var(--history-text-primary);
  transition: color 0.3s ease;
}

.image-block strong {
  color: var(--history-text-secondary);
  transition: color 0.3s ease;
}

.defect-block {
  background: var(--bgcolor);
  border: 1px solid var(--history-border);
  padding: 12px;
  margin-top: 10px;
  border-radius: 6px;
  transition: background-color 0.3s ease, border-color 0.3s ease;
}

.defect-block ul li {
  margin-left: 1em;
  list-style: none;
  color: var(--history-text-primary);
  transition: color 0.3s ease;
}

.suggestion {
  font: 16px aria, sans-serif;
  background: var(--card-bg);
  padding: 15px;
  white-space: pre-wrap;
  border-radius: 6px;
  color: var(--history-text-primary);
  transition: background-color 0.3s ease, color 0.3s ease;
}

/* 添加的图片预览样式 */
.image-preview {
  margin-bottom: 15px;
  padding: 10px;
  background-color: var(--bgcolor);
  border-radius: 6px;
  border: 1px solid var(--history-border);
}

.preview-image {
  max-width: 100%;
  max-height: 300px;
  cursor: pointer;
  border-radius: 4px;
  margin: 10px 0;
  transition: transform 0.2s;
}

.preview-image:hover {
  transform: scale(1.02);
}

.image-url {
  font-size: 12px;
  color: var(--history-text-secondary);
  word-break: break-all;
  margin-top: 5px;
}
</style>
